#!/bin/sh
#创建SVN版本库，
basefuncs=`which functions.sh`
if [ "$basefuncs" != "" ] ;then
    . $basefuncs
else
    basefuncs=`dirname $0`/functions.sh
    echo "$PWD"
    echo "funcs=$basefuncs"
    if [ "$basefuncs" != "" ] ;then
		. $basefuncs
		else
		exit
	fi
fi


#默认参数
#仓库本地路径
#default_repo_path="/home/gphone/repos" #服务器上的路径
DEFAULT_REPO_ROOT_PATH="/home/gphone/repos"
repo_root_path=""
# 仓库Http访问地址 "http://localhost/svn"
DEFAULT_REPO_ROOT_HTTP="http://172.20.120.214/repositories"
repo_root_http=""
#文档仓库的地址
DEFAULT_DOCSNTOOLS="DocsAndTools/Docs/Qualcomm"
docsntools=""
runplace="/tmp/"
ADMIN_GROUP="scm_admin"
mode=
cur_project=


function ShowUsage()
{
	echoText "Useage:" GREEN >&2
	echoText "use by auto  : svn-create-repo.sh <-a|--auto> <YourProjectName> " RED  >&2
	echoText "use by manual: svn-create-repo.sh <-m|--manual> " RED >&2
	echoText "for help     : svn-create-repo.sh <-h|--help> " RED >&2
}

#获得SVN Project在DocsAndTools下需要新增的目录，http路径,import时需要
#服务器上的地址为：http://172.20.127.15/repositories/DocsAndTools/Docs//Qualcomm/TD1014/branch/
function GetProjectDocsHttpPath()
{
	local project=$1
	echo "$repo_root_http/$docsntools/$project/"
}
function GetProjectSrcsHttpPath()
{
	local project=$1
	echo "$repo_root_http/$project/"
}
#创建项目所需的父目录和子目录，创建版本库和DocsAndTools下对应的branch需要用到
# $1 
function CreateFakeDir()
{
local project=$1   
#DocsAndTools
mkdir -p $runplace/$project/docs/branch/{REQ,PCE,MMI,HLD,LLD,SOP,Test/{UT,ST,IT,CR},UE/{HR,UES,GUI,MUI}}
mkdir -p $runplace/$project/docs/trunk/{REQ,PCE,MMI,HLD,LLD,SOP,Test/{UT,ST,IT,CR},UE/{HR,UES,GUI,MUI},Reference,PM}
mkdir -p $runplace/$project/docs/tags/{REQ,PCE,MMI,HLD,LLD,SOP,Test}
mkdir -p $runplace/$project/docs/release/
mkdir -p $runplace/$project/docs/SW_Data/{TF_Data,MMI_SW_Data,TT_SW_Data,ST_SW_Data}
mkdir -p $runplace/$project/docs/Third_Part_Soft/branch/{REQ,MMI,ST,Design}
mkdir -p $runplace/$project/docs/Third_Part_Soft/trunk/{REQ,MMI,ST,Design,Reference,PM}
mkdir -p $runplace/$project/docs/Third_Part_Soft/SW_Data/{MMI_SW_Data,TT_SW_Data}
#sources
mkdir -p $runplace/$project/srcs/{3src,branch,trunk,release,tags,special,RDline}
}

function DeleteFakeDir()
{
	local project=$1  
	rm -rf $project
}

function CreateSvnRepo()
{
  local repo_root=$1
  local repo_project=$2
  if [ -d $repo_root/$repo_project ]; then #仓库下已存在此版本库！
	  echoText "There's already has project $repo_project at $repo_root .Exit now... " RED >&2
	  exit
  else
	  sudo svnadmin create --fs-type=fsfs  $repo_root/$repo_project
	  sudo chmod -R o+rw $repo_root/$repo_project
	  sudo sed -i "s/# anon-access = read/anon-access = none/g" 		$repo_root/$repo_project/conf/svnserve.conf
	  sudo sed -i "s/# auth-access = write/auth-access = write/g" 	$repo_root/$repo_project/conf/svnserve.conf
	  sudo sed -i "s/# password-db = passwd/password-db = ..\/..\/etc\/passwd-${repo_project}_access_by_svn/g"   $repo_root/${repo_project}/conf/svnserve.conf
	  sudo sed -i "s/# authz-db = authz/authz-db = ..\/..\/etc\/authz-${repo_project}/g"   $repo_root/$repo_project/conf/svnserve.conf
	  sudo cp $repo_root/$repo_project/hooks/pre-revprop-change.tmpl  $repo_root/$repo_project/hooks/pre-revprop-change
	  sudo chmod a+x $repo_root/$repo_project/hooks/pre-revprop-change
	  CreateFakeDir $repo_project
  fi
}
function ConfigPasswdAuthz()
{
	local project=$1
	cd $repo_root_path/etc/
	ln -s authz-common   authz-$project
        echo "
[${project}:/]
compiler = rw" >> authz-$project
	ln -s passwd-common_access_by_http  passwd-${project}_access_by_http
	ln -s passwd-common_access_by_svn  passwd-${project}_access_by_svn
	cd -
# 	if [ ! -d $repo_root_path/etc/ ]; then
# 		echoText "No dir $repo_root_path/etc/ .Now create it." RED
# 		mkdir -p $repo_root_path/etc/
# 	fi
# 	#svn方式登录密码文件	
# 	if [ ! -f $repo_root_path/etc/passwd-${project}_access_by_svn ]; then
# 		echoText "Create passwd-${project}_access_by_svn at $repo_root_path/etc/" RED
# 		cat >>$repo_root_path/etc/passwd-${project}_access_by_svn<<EOF
# [users]
# # harry = harryssecret
# # sally = sallyssecret
# $ADMIN_USERNAME = $ADMIN_PASSWORD
# EOF
# 	else
# 		echoText "Alredy has  svn passwd file"
# 	fi
# 	
# 	if [ ! -f $repo_root_path/etc/passwd-${project}_access_by_http ]; then
# 		echoText "Create passwd-${project}_access_by_http at $repo_root_path/etc/" RED
# 		htpasswd -bc $repo_root_path/etc/passwd-${project}_access_by_http $ADMIN_USERNAME $ADMIN_PASSWORD
# 	else
# 		echoText "Alredy has  http passwd file"
# 	fi
# 	
# 	if [ ! -f $repo_root_path/etc/authz-${project} ] ;then
# 		echoText "Create authz-${project} at $repo_root_path/etc/" RED
# 	cat >>$repo_root_path/etc/authz-${project}<<EOF
# [groups]
# # harry_and_sally = harry,sally
# # harry_sally_and_joe = harry,sally,&joe
# g_${project}_admin = $ADMIN_USERNAME
# 


# 	else
# 		echoText "Alredy has  authz file [$repo_root_path/etc/authz-${project}] file" RED
# 	fi
	
}

function ImportDocsDirs()
{
  local project=$1
  local docsHttpPath=`GetProjectDocsHttpPath $project` 
	svn import $runplace/$project/docs/ $docsHttpPath  --username compiler -m "initial DocsAndTools branch for $project  "
}
function InitRepoProjectDirs()
{
	local project=$1
	local srcsHttpPath=`GetProjectSrcsHttpPath $project` 
	svn import $runplace/$project/srcs/ $srcsHttpPath  --username compiler -m "initial repo for $project  "
	
}
#将仓库添加到apache2的配置中
function AddToApache()
{
	local project=$1
# 	if [ -f /etc/apache2/sites-enabled/$project ]; then
	  #此句代码有问题！未能正确 完全地 匹配项目名称，eg. 存在TD1104IMG则无法创建TD1104
	  isExist=`cat /etc/apache2/sites-enabled/svn-default | grep Location | grep "${project}>"` 
	if [ "$isExist" != "" ]; then
	  echoText "WARNING:$project Already has add to Apache2!!!. " RED
	  echoText "SEE /etc/apache2/sites-enabled/$project " RED
	else
		echoText "add $project  to Apapche2" RED
		lines=(`cat /etc/apache2/sites-enabled/svn-default | grep -n -H "</Location" | awk -F ':' '{print $2}'`)
		lineCount=$(( ${#lines[*]} - 1 ));
		lineNo=${lines[$lineCount]};

		sudo chmod 777 -R /etc/apache2/sites-enabled/
		apache_config="\n<Location /repositories/$project>\nDAV svn\nSVNPath  $repo_root_path/$project\nAuthType Basic\nAuthName \"Your repository name\"\nAuthUserFile       $repo_root_path/etc/passwd-${project}_access_by_http\nAuthzSVNAccessFile $repo_root_path/etc/authz-${project}\nRequire valid-user\n</Location>\n"

# 		echoText "lineNo: $lineNo ;\n apache_config: ${apache_config}" RED
		sudo sed "${lineNo}a\\${apache_config}" -i /etc/apache2/sites-enabled/svn-default

	fi  
}

function RestarApache()
{
	local resault=`question "It's going to RESTART APACHE2, will you continue?" 1 yes`
	if [ $resault == "yes" ]; then
		echoText "Restart Apache...."  RED
		sudo /etc/init.d/apache2 restart
	else
		echoText "The new project is NOT ACTIVATED!, you need to restart APACHE2 yourself!"  RED
		exit
	fi
}

mode=$1
cur_project=$2
resault1=
resault2=
echoText "begin ...." RED
case $mode in
	-a|--auto)
	  if [ $cur_project == "" ]; then
		  $(ShowUsage)
	  else
		  repo_root_path=$DEFAULT_REPO_ROOT_PATH
		  repo_root_http=$DEFAULT_REPO_ROOT_HTTP
		  docsntools=$DEFAULT_DOCSNTOOLS
		  #创建SVN版本库
		  if [ -d $repo_root_path/$cur_project ]; then 
			echoText "Already has a Project named as [$cur_project] at $repo_root_path .now EXIT" RED
			 exit
		  else
			CreateSvnRepo $repo_root_path $cur_project
			AddToApache $cur_project
			ConfigPasswdAuthz $cur_project
			RestarApache
			InitRepoProjectDirs $cur_project 
			ImportDocsDirs $cur_project 
			DeleteFakeDir $cur_project 
			echoText "All Finished, now you can browse you Project at:" GREEN
			echoText "`GetProjectSrcsHttpPath $cur_project `" RED
		  fi
		  fi
	  ;;
	-m|manual)
		repo_root_path=`question "输入SVN版本库本的根目录:" 	2 $DEFAULT_REPO_ROOT_PATH`
		repo_root_http=`question "输入SVN版本库网络访问路径:" 	2 $DEFAULT_REPO_ROOT_HTTP`
		cur_project=`question "输入要创建的版本库名称:" 2  NewSvnRepo`
		docsntools=`question "文档存放的地址:" 2  $DEFAULT_DOCSNTOOLS`
		####### 开始创建 ##############
		#创建SVN版本库
		  if [ -d $repo_root_path/$cur_project ]; then 
			echoText "Already has a Project named as [$cur_project] at $repo_root_path .now EXIT" RED
			 exit
		  else
			CreateSvnRepo $repo_root_path $cur_project
			AddToApache $cur_project
			ConfigPasswdAuthz $cur_project
			sudo /etc/init.d/apache2 restart
			 resault1=`question "It's going to Initial project $cur_project with default dirs, will you continue?" 1 no`
			if [ $resault1 == "yes" ]; then
				InitRepoProjectDirs $cur_project 
			fi

			 resault2=`question "It's going to Add docsDir for $cur_project, will you continue?" 1 no`
			if [ $resault2 == "yes" ]; then
				ImportDocsDirs $cur_project 
			fi
			DeleteFakeDir $cur_project 
			echoText "All Finished, now you can browse you Project at:" GREEN
			echoText "`GetProjectSrcsHttpPath $cur_project `" RED
		  fi
	;;
	-h|--help)
		$(ShowUsage)
	;;	
	*)
		$(ShowUsage)
	;;	
esac

exit
#确认版本库的基本信息
#repo_root_path=`question "输入SVN版本库本地根目录:" 	2 $DEFAULT_REPO_ROOT_PATH`
#repo_root_http=`question "输入SVN版本库网络访问路径:" 	2 $DEFAULT_REPO_ROOT_HTTP`
#cur_project=`question "输入要创建的版本库名称:" 	2 "NewSvnRepo"`




